package fr.mma.livraison.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import fr.mma.livraison.model.dto.ApplicationDTO;
import fr.mma.livraison.model.dto.PomPortailDTO;

public class PortailParentReader {

	private final XPath xpath = XPathFactory.newInstance().newXPath();

	private static PortailParentReader instance;

	protected PortailParentReader() {
		//RAS
	};

	public static PortailParentReader getInstance() {
		if (instance == null) {
			instance = new PortailParentReader();
		}
		return instance;
	}

	public PomPortailDTO read(final InputStream input) {
		final PomPortailDTO portailParent = new PomPortailDTO();
		try {
			final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			final Document document = builder.parse(input);

			final List<ApplicationDTO> applicationList = recupererApplication(document);
			portailParent.getApplicationList().addAll(applicationList);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return portailParent;
	}

	protected List<ApplicationDTO> recupererApplication(final Document document) {
		final List<ApplicationDTO> applicationList = new ArrayList<ApplicationDTO>();
		try {
			final NodeList nodes = (NodeList) xpath.evaluate("/project/properties/*", document, XPathConstants.NODESET);
			for (int i = 0; i < nodes.getLength(); i++) {
				final Node node = nodes.item(i);
				if (isVersionNode(node)) {
					final String applicationName = StringUtils.remove(node.getNodeName(), ".version");
					final ApplicationDTO application = new ApplicationDTO(applicationName);
					application.setVersion(node.getTextContent());
					applicationList.add(application);
				}
			}
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return applicationList;
	}

	protected boolean isVersionNode(final Node node) {
		return StringUtils.contains(node.getNodeName(), "version");
	}
}
